<?php

namespace app\api\controller;

use app\common\lib\Param;
use app\common\lib\Show;
use app\common\lib\Str;
use app\Request;
use think\facade\Cache;
use think\response\Json;

class Message extends ApiBase
{
    public function index(): Json
    {
        $page = input("page", 0, "intval");
        $limit = input("limit", 0, "intval");

        $messageBis = new \app\common\business\Message();

        $map = [];
        try {
            $list = $messageBis->getListByWhereWithOrder($map,$page,$limit,'sort desc,id desc','id,content,reply_content,reply_time,create_time');
            $count = $messageBis->getCountByWhere($map);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }

        $list = $messageBis->resetInfo($list);
        $result = [
            'count'=>$count,
            'list'=>$list
        ];
        return Show::success($result);
    }

    public function detail(): Json
    {
        $id = input("id", 0, "intval");

        $messageBis = new \app\common\business\Message();

        try {
            $info = $messageBis->getNormalById($id);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }

        !empty($info) && $info = $messageBis->resetInfo([$info]);
        return Show::success($info);
    }

    /**
     * 新增/保存数据
     * @return Json
     */
    public function save(): Json
    {
        list($content) = Param::postMore([
            ['content',''],
        ], $this->request, true);

        $ip = request()->ip();
        $data=[
            'status'=>0,
            'sort'=>0,
            'content'=>$content,
            'request_ip'=> $ip//当前请求IP，用于限制每日留言数
        ];
        $validate = new \app\admin\validate\Message();
        $scene='add';
        if (!$validate->scene($scene)->check($data)) {
            return Show::error([], $validate->getError());
        }

        $messageBis = new \app\common\business\Message();
        try {
            $messageBis->submitLimitByIp($ip);
            $result = $messageBis->save($data);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "保存成功");
        }
        return Show::error([], '保存失败');
    }
}
